<?php
 
class Database {
 
	// Private variables
    private $handler;
    private $database;
	private $error;
 
	// Public variables
    public $result;
    public $num_rows;
 	
	/**
     * opens database connection
	 */
	function __construct($database){
		$this->database = $database;
		$this->connect();
	}
	
    /**
     * connect(): Connect to SQLite
     */
    function connect() {
		$this->handler = sqlite_open($this->database, 0666, $this->error); 
    }
 
    /**
     * Destructor: Clean up
     */
    function __destruct() {
		sqlite_close($this->handler);
    }
 
    /**
     * select(): Select a row or rows from the DB
     * @param string $table     Table name
     * @param array $columns    Either '*' or a list of columns to select
     * @param array $where      column => value
     * @param array $order_by   column1 => DESC, column2 => ASC
     * @param array $limit      1 or 30 or 0, 30 or 30, 60 (etc)
     * @param bool $debug       Returns query string if true
     * @returns SQLite resource
     */
    function select($table, $columns, $where = '', $order_by = '', $limit = '', $debug = 0) {
 
        if ( $table == '' || !sizeof($columns)) { return; }
 
        // Set up columns
        $data = '';
        $tmp = '';
        if ( $columns != '*' ) {
 
            if ( is_array($columns) ) {
 
                foreach($columns as $column) { 
                    $data .= '' . $column . ', '; 
                }
 
                $columns = preg_replace( "/, $/" , "" , $data);
 
            } else { 
                $columns = '' . $columns . ''; 
            } 
        }
 
        // Set up the WHERE
        if ( !empty($where) ) { 
            $tmp = '';
            foreach ($where as $key => $val) { 
                $tmp .= '' . $key . " = '" . $this->escape_str($val) . "' AND "; 
            }
 
            $where = ' WHERE ' . preg_replace( "/ AND $/" , "" , $tmp); 
        }
 
        // Set up the ORDER BY
        $tmp = '';
        if ( !empty($order_by) ) { 
            if ( is_array($order_by) ) { 
                foreach($order_by as $val => $order) { 
                    $tmp .= '' . $val . ' ' . $order . ', '; 
                }
 
                $order_by = ' ORDER BY ' . preg_replace( "/, $/" , "" , $tmp); 
            } else { 
                $order_by = ' ORDER BY ' . $order_by; 
            } 
        }
 
        // Set up the LIMIT
        $tmp = '';
        if ( !empty($limit) ) { 
            if ( is_array($limit) ) { 
                foreach ($limit as $num) { 
                    $tmp .= $num . ', '; 
                }
 
                $limit = ' LIMIT ' . preg_replace( "/, $/" , "" , $tmp); 
            } else { 
                $limit = ' LIMIT ' . $limit; 
            } 
        }
 
        $query = 'SELECT ' . $columns . ' FROM ' . $table . '' . $where . $order_by . $limit;
        
        // Return query string for debugging purposes or just do the query
        if ( $debug ) { 
            return $query; 
        } else { 
            // Perform the query
            return $this->query($query); 
        } 
    }
 
    /**
     * insert(): Insert data into a table
     * @param string $table Table to insert into
     * @param array $data   The column name & data
     * @param boolean $slashes True if you want to add 's to the string
     * @returns boolean True if successful, false if not.
     */
    function insert($table, $data, $slashes = false) {
 
        if ( $table == '' || $data == '' ) { return; }
 
        $fields = '';      
        $values = '';
 
        foreach($data as $key => $val) { 
            $fields .= '\'' . $key . '\', ';
            $val = ( $slashes == true ) ? addslashes($val) : $val;
            $values .= "'" . addslashes( stripslashes($val) ) . "'" . ', '; 
        }
 
        $fields = preg_replace( "/, $/" , "" , $fields);
        $values = preg_replace( "/, $/" , "" , $values);
 
        sqlite_query($this->handler, 'INSERT INTO \'' . $table . '\' (' . $fields . ') VALUES (' . $values . ')'); 
    }
 
    /**
     * update(): Update data into a table
     * @param string $table Table to insert into
     * @param array $data   The column name & data
     * @param boolean $slashes True if you want to add 's to the string
     * @returns boolean True if successful, false if not.
     */
    function update($table, $data, $where, $slashes = false) {
 
        if ( $table == '' || $data == '' || $where == '') { return; }
 
        $string  = '';
        $tmp = '';
 
        foreach($data as $key => $val) {
            $string .= '' . $key . " = '" . $this->escape_str($val) . "', ";
        }
 
        $string = preg_replace( "/, $/" , "" , $string);
 
        if ( is_array($where) ) { 
            foreach ($where as $key => $val) { 
                $tmp .= $key . " = '" . $this->escape_str($val) . "' AND "; 
            }
 
            $where = preg_replace( "/AND $/" , "" , $tmp); 
        } else { 
            $where = $where; 
        }
 
        sqlite_query($this->handler, 'UPDATE ' . $table . ' SET ' . $string . ' WHERE ' . $where);
    }
 
    /**
     * delete(): Delete a row from a table
     * @param string $table Table to insert into
     * @param array $data   The column name & data
     */
    function delete($table, $data) { 
        if ( $table == '' || $data == '') { return; }
  
        sqlite_query($this->handler, 'DELETE FROM ' . $table . ' WHERE ' . key($data) . " = '" . $data[key($data)] . "'"); 
    }
 
    /**
     * query(): Query from SQLite. 
     * @param string $query The SQLite query
     * @returns SQLite resource
     *
     * Warning: This function is only ment to be called manually if being used in 
     * a development environment because it does not do any input validation.
     */
    function query($query) {
 
        if ( $query == '') { return; }
		
        $this->result = sqlite_query($this->handler, $query);
        $this->num_rows = sqlite_num_rows($this->result);

		$tmp_array = array();
		while ($row = sqlite_fetch_array($this->result, SQLITE_ASSOC)) {
			array_push($tmp_array, $row); 
		}

		$this->result = $tmp_array;
		return $this->result; 
    }
 
    function escape_str($string) { 
    	if ( is_array($string) ) { 
    		foreach($string as $key => $val) { 
    			$str[$key] = $this->escape_str($val); 
    		}
 
    		return $str;
		}
 
    	if ( function_exists('sqlite_escape_string') ) { 
			return sqlite_escape_string( stripslashes($string) ); 
		} else { 
        	return addslashes( stripslashes($string) ); 
    	} 
    } 
}